<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { deviceApi, deviceById, devicegroupkeyvalueApi, devicegroupkeyvalueById } from '@T2/service/api.ts';
import { useCurrentWatchStore } from '@T2/store/users.ts';

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;

const props = defineProps({
  type: {
    type: String,
    validator(value) {
      return ['新增', '编辑', '详情'].includes(value);
    },
    required: true,
  },
  info: {
    type: Object,
    required: true,
  },
  device: {
    type: [null, Object],
    required: true,
  },
  devicegroupkeys: {
    type: Array,
    required: true,
  },
});
const emits = defineEmits(['closed', 'refresh']);
const show = ref(true);
const isDetail = computed(() => props.type === '详情');
const handleClosed = () => {
  emits('closed');
}

const deviceForm = reactive({
  data: {
    name: props.device?.name,
    code: props.device?.code,
  },
  keyvalue: [],
});
onMounted(async () => {
  deviceForm.keyvalue = await createKeyValueList();
});
const createKeyValueList = async () => {
  let keyValueList = [];
  if (props.type === '新增') {
    keyValueList = props.devicegroupkeys.map(i => { return { name: i.name, value: '', devicegroupkey: i.id } });
  } else if (props.type === '编辑' || props.type === '详情') {
    if (!props.device.id) {
      ElMessage.error('未知故障！');
      return;
    }
    
    await checkkeyvalueMul(); //检查是否存在同一个key下多条值，多余的删除
    keyValueList = props.devicegroupkeys.map(i => { 
      const [ keyvalue0 ] = i.children || [];
      if (keyvalue0) {
        return { id: keyvalue0.id,  name: i.name, value: keyvalue0.value, devicegroupkey: i.id };
      } else {
        return { name: i.name, value: '', devicegroupkey: i.id };
      }
    });
  }
  return keyValueList;
}
const checkkeyvalueMul = async (keys, values) => {
  for (const item of props.devicegroupkeys) {
    if (item.children?.length > 1) {
      for (const [index, keyvalue]  of item.children.entries()) {
        if (index > 0) {
          await deleteDevicegroupkeyvalue(keyvalue.id);
        }
      }
    }
  }
}
const deleteDevicegroupkeyvalue = (id) => {
  return new Promise((resolve, reject) => {
    devicegroupkeyvalueById({
      method: 'delete',
      id,
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}

const submitLoading = ref(false);
const handleSubmit = async () => {
  submitLoading.value = true;
  if (!deviceForm.data.name) {
    ElMessage.error('请输入设备名称！');
    return;
  }
  if (!deviceForm.data.code) {
    ElMessage.error('请输入设备位号！');
    return;
  }
  
  let deviceRes = null;
  if (props.type === '新增') {
    deviceRes = await addDevice();
    if (!deviceRes?.id) {
      ElMessage.error('创建设备失败！');
      return;
    }
  } else if (props.type === '编辑') {
    if (!props.device?.id) {
      ElMessage.error('未知故障！');
      return;
    }
    deviceRes = await editDevice();
  }
  
  for (const item of deviceForm.keyvalue) {
    if (item.id) {
      /* 编辑devicegroupkeyvalue */
      await editDevicegroupkeyvalue(item, deviceRes);
    } else if (item.value !== '') {
      /* 新增devicegroupkeyvalue */
      await addDevicegroupkeyvalue(item, deviceRes);
    }
  }
  submitLoading.value = false;
  handleClosed();
  emits('refresh');
}

const addDevice = () => {
  return new Promise((resolve, reject) => {
    deviceApi({
      method: 'post',
      data: {
        ...deviceForm.data,
        project: curProject.id,
        unit: props.info.unit,
        devicegroup: props.info.devicegroup,
      }
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}
const editDevice = () => {
  return new Promise((resolve, reject) => {
    deviceById({
      method: 'patch',
      id: props.device.id,
      data: {
        ...deviceForm.data,
      }
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}

const addDevicegroupkeyvalue = (item, deviceRes) => {
  return new Promise((resolve, reject) => {
    devicegroupkeyvalueApi({
      method: 'post',
      data: {
        project: curProject.id,
        devicegroup: props.info.devicegroup,
        device: deviceRes.id,
        devicegroupkey: item.devicegroupkey,
        value: item.value,
      }
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}
const editDevicegroupkeyvalue = (item, deviceRes) => {
  return new Promise((resolve, reject) => {
    devicegroupkeyvalueById({
      method: 'patch',
      id: item.id,
      data: {
        value: item.value,
      }
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}

</script>

<template>
  <div>
    <el-dialog
      v-model="show"
      :title="props.type + '设备' + `（${ props.info?.devicegroup_name }）`"
      :show-close="false"
      width="980px"
      @close="handleClosed()"
    >
      <div class="box-item flex-column">
        <label class="title-type">必填参数</label>
        <div class="grid-box">
          <div :class="isDetail ? 'grid-item2 flex' : 'grid-item1 flex-column'">
            <label class="form-name required">设备名称：</label>
            <span v-if="isDetail">{{ deviceForm.data.name }}</span>
            <el-input v-model="deviceForm.data.name" placeholder="请输入" v-else></el-input>
          </div>
          <div :class="isDetail ? 'grid-item2 flex' : 'grid-item1 flex-column'">
            <label class="form-name required">设备位号：</label>
            <span v-if="isDetail">{{ deviceForm.data.code }}</span>
            <el-input v-model="deviceForm.data.code" placeholder="请输入" v-else></el-input>
          </div>
        </div>
      </div>
      <div class="box-item flex-column">
        <label class="title-type">核心参数</label>
        <div class="grid-box">
          <div :class="isDetail ? 'grid-item2 flex' : 'grid-item1 flex-column'" v-for="item in deviceForm.keyvalue.slice(0, 8)">
            <label class="form-name">{{ item.name }}：</label>
            <span v-if="isDetail">{{ item.value }}</span>
            <el-input v-model="item.value" placeholder="请输入" v-else></el-input>
          </div>
        </div>
      </div>
      <div class="box-item flex-column">
        <label class="title-type">辅助参数</label>
        <div class="grid-box">
          <div :class="isDetail ? 'grid-item2 flex' : 'grid-item1 flex-column'" v-for="item in deviceForm.keyvalue.slice(8)">
            <label class="form-name">{{ item.name }}：</label>
            <span v-if="isDetail">{{ item.value }}</span>
            <el-input v-model="item.value" placeholder="请输入" v-else></el-input>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <template v-if="props.type === '详情'">
            <el-button type="primary" @click="handleClosed()">关 闭</el-button>
          </template>
          <template v-else>
            <el-button @click="handleClosed()">取 消</el-button>
            <el-button type="primary" @click="handleSubmit()" :loading="submitLoading" v-prevent-rapid-click>确 定</el-button>
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.box-item {
  margin-bottom: 36px;
}
.title-type {
  font-weight: 600;
  font-size: 16px;
  color: #4C4C4C;
  margin-bottom: 16px;
}
.grid-box {
  display: grid;
  gap: 16px 24px;
  grid-template-columns: 1fr 1fr 1fr;
}
.grid-item1 {
  
}
.grid-item2 {
  align-items: center;
  span {
    font-weight: 400;
    font-size: 14px;
    color: #111111;
  }
}
.form-name {
  font-weight: 400;
  font-size: 14px;
  line-height: 16px;
  color: #666666;
  margin-bottom: 4px;
  position: relative;
  &.required::before {
    content: '*';
    position: absolute;
    top: 0;
    left: -8px;
    color: #ff0000;
  }
}
</style>
<style scoped>
:deep(.el-dialog) {
  padding: 0;
}
:deep(.el-dialog__header) {
  padding: 24px 24px 16px;
  border-bottom: 1px solid #EDEFF3;
}
:deep(.el-dialog__body) {
  padding: 16px 24px;
}
:deep(.el-dialog__footer) {
  padding: 16px 24px;
}
</style>